<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>STOMP WebSocket Demo</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/sockjs-client/1.5.1/sockjs.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/stomp.js/2.3.3/stomp.min.js"></script>
</head>
<body>
    <h2>WebSocket STOMP Demo</h2>
    <input type="text" id="messageInput" placeholder="Type a message..." />
    <button onclick="sendMessage()">Send Message</button>
    <div id="messages"></div>

    <script>
        let stompClient = null;

        // 连接到 WebSocket 端点
        function connect() {
            const socket = new SockJS('http://localhost:8088/perf/ws');
            stompClient = Stomp.over(socket);
            stompClient.connect({}, function (frame) {
                console.log('Connected: ' + frame);
                stompClient.subscribe('/topic/sdk', function (message) {
                    showMessage(message.body);
                });
            });
        }

        // 断开连接
        function disconnect() {
            if (stompClient !== null) {
                stompClient.disconnect();
            }
            console.log("Disconnected");
        }

        // 发送消息到服务端
        function sendMessage() {
            const message = document.getElementById("messageInput").value;
            stompClient.send("/app/send", {}, message);
        }

        // 显示消息
        function showMessage(message) {
            const messagesDiv = document.getElementById("messages");
            const newMessage = document.createElement("div");
            newMessage.appendChild(document.createTextNode(message));
            messagesDiv.appendChild(newMessage);
        }

        // 页面加载时连接
        window.onload = function () {
            connect();
        };

        // 页面卸载时断开连接
        window.onbeforeunload = function () {
            disconnect();
        };
    </script>
</body>
</html>
